package org.nuonuo.sdk.valid;

import javax.validation.ConstraintViolation;
import javax.validation.ValidationException;
import java.util.Set;

/**
 * @version 1.0
 * @Author az
 * @Date 2023-09-19 11:30:21
 * @ClassName Validator
 * @Description TODO
 */
public class Validator {

    private static javax.validation.Validator validator;

    static {
        validator = javax.validation.Validation.buildDefaultValidatorFactory().getValidator();
    }

    public void valid() {
        Validator.validator(this);
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     */
    public static void validator(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new ValidationException(constraint.getMessage());
        }
    }
}
